package edu.esiag.isidis.fi.LBTest;

import java.io.IOException;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import edu.esiag.isidis.fi.lb.interfaces.IEntity;

public class EntityReciver extends Thread implements IEntity<Byte>,Serializable{
	
	String host;
	int port;
	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public int getMax() {
		return Max;
	}

	public void setMax(int max) {
		Max = max;
	}

	public boolean isActive() {
		return active;
	}

	public void setActive(boolean active) {
		this.active = active;
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = -3483813376557799834L;
	private String mName;
	private List<Byte> mNames = Collections.synchronizedList(new ArrayList<Byte>());
	int Max;
	boolean active;
	
	
	
	private static Logger logger = Logger.getLogger("LoadBalancingTest");
	
	public EntityReciver(String mName , int max,String host,int port) {
		// TODO Auto-generated constructor stub
		this.mName=mName;
		this.Max=max;
		FileHandler fileHandler;
		try {
			fileHandler = new FileHandler("KhalidElGhoumari.log");
			logger.addHandler( fileHandler);
			SimpleFormatter formatter = new SimpleFormatter();  
	        fileHandler.setFormatter(formatter);  
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		start();
	}
	
	public void runProcess(Byte information) {
		synchronized (mNames) {
			mNames.add(information);	
		}
	}

	public boolean isActivate() {
		// TODO Auto-generated method stub
		return active;
	}

	public boolean isBusy() {
		// TODO Auto-generated method stub
		return (mNames.size()==Max);
	}

	public Object getIdentifier() {
		// TODO Auto-generated method stub
		return mName;
	}

	public void activate() {
		// TODO Auto-generated method stub
		active=true;
	}

	public void disable() {
		// TODO Auto-generated method stub
		active=false;
	}
	
	@Override
	public void run() {
		while(true){
			try{
				synchronized (mNames) {
					if(mNames.size() > 0){
						String str=Integer.toBinaryString(mNames.remove(0));
						logger.log(Level.INFO, mName + " Reception(" + mNames.size() +  ")" + str);
						}
				}
				int random = (int)(Math.random() * (1000));
				Thread.sleep(random);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}
}
